//初始化整个游戏的精灵，作为游戏开始的入口
import ResourceLoader from './js/base/ResourceLoader.js'
import Director from './js/Director.js'
import BackGround from './js/runtime/BackGround.js'
import DataStore from './js/base/DataStore.js'
import Land from './js/runtime/Land.js'
import Birds from './js/player/Birds.js'
import StartButton from './js/player/StartButton.js'
import Score from './js/player/Score.js'

export default class {
  constructor() {
    // this.canvas = document.getElementById('game_canvas')
    this.canvas = wx.createCanvas()
    this.ctx = this.canvas.getContext('2d')
    this.dataStore = DataStore.getInstance()
    this.director = Director.getInstance()
    const loader = ResourceLoader.create()
    loader.onLoaded((map) => this.onResourceFirstLoaded(map))
    // this.director.isGameOver = true //todo
  }

  onResourceFirstLoaded(map) {
    this.dataStore.canvas = this.canvas
    this.dataStore.ctx = this.ctx
    this.dataStore.res = map
    this.createBackgroundMusic()
    this.init()
  }

  createBackgroundMusic() {
    const bgm = wx.createInnerAudioContext()
    bgm.autoplay = false
    bgm.loop = true
    bgm.src = `audios/bgm.mp3`
    this.dataStore.bgm = bgm
  }

  init() {
    // this.dataStore.isGameOver = true
    this.dataStore
    .put('pencils', [])
    .put('background', BackGround)
    .put('land', Land)
    .put('birds', Birds)
    .put('startButton', StartButton)
    .put('score', Score)
    this.registerEvent()
    this.director.createPencils()
    this.director.run()
    this.dataStore.bgm.play()
  }

  registerEvent() {
    // this.canvas.addEventListener('touchstart', evt => {
    //   evt.preventDefault()
    //   if (this.director.isGameOver) {
    //     // this.director.isGameOver = false
    //     console.info('游戏开始')
    //     this.init()
    //     return
    //   }
    //   this.director.birdsEvent()
    // })
    wx.onTouchStart(() => {
      if (this.director.isGameOver) {
        // this.director.isGameOver = false
        console.info('游戏开始')
        this.init()
        return
      }
      this.director.birdsEvent()
    })
  }
}
